import {
	HTTP_REQUEST_URL,
	HEADER,
	TOKENNAME
} from '@/config/app';
import Cache from './cache'
import {againWechatLogin} from './wx'
/**
 * 发送请求
 */
function baseRequest(url, method, data, {
	noAuth = false,
	noVerify = false
}) {
	let Url = HTTP_REQUEST_URL,
		header = HEADER;
	const token=Cache.get(TOKENNAME)
	if (!noAuth) {
		//登录过期自动登录
		if (!token) {
			// toLogin();
			return Promise.reject({
				msg: `未登录`,
				code:401
			});
		}
	}
	if (token) header[TOKENNAME] = 'Bearer ' + token;

	return new Promise((reslove, reject) => {
		uni.request({
			url: Url + url,
			method: method || 'GET',
			header: header,
			data: data || {},
			success: (res) => {
				if (noVerify)
					reslove(res.data, res);
				else if (res.data.code == 0)
					reslove(res.data, res);
				else if ([401].includes(res.data.code)) {
					// toLogin();
					againWechatLogin()
					reject(res.data);
				} else if (res.data.code !=0) {
					uni.showToast({
						icon:'none',
						title: res.data.msg,
						duration: 2000
					});
					reject(res);
				} else
					reject(res.data.msg || `系统错误`);
			},
			fail: (msg) => {
				console.log(msg)
				let data = {
					mag: `请求失败`,
					status: 1 //1没网
				}
				reject(data);
			}
		})
	});
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
});



export default request;
